﻿using Core.Domain.Entities;
using Finbuckle.MultiTenant;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace Infrastructure.Persistence.Configurations;

public class RolePermissionConfiguration : IEntityTypeConfiguration<RolePermission>
{
    public void Configure(EntityTypeBuilder<RolePermission> builder)
    {
        builder
          .ToTable("RolePermissions", "identity")
          .IsMultiTenant();

        builder.HasKey(u => u.Id);

        builder.Property(rp => rp.AccessState)
               .HasConversion<string>()
               .HasMaxLength(100)
               .IsRequired();

        builder.HasOne(rp => rp.Role)
            .WithMany(r => r.Permissions)
            .HasForeignKey(rp => rp.RoleId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasOne(o => o.Permission)
            .WithMany(r => r.RolePermissions)
            .HasForeignKey(o => o.PermissionId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(rp => rp.RoleId);
        builder.HasIndex(rp => rp.PermissionId);
    }
}
